package com.hailan.demo01;

//基本的买票的例子

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SaleTicketDemo01
 * @Description TODO
 * 线程就是一个单独的资源类，没有任何附属的操作！
 * @Author hailan
 * @Date 2020-08-31 19:49
 * @Version 1.0
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();

        new Thread(() -> {
            for (int i = 0; i < 60; i++)
                ticket.sale();

        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 60; i++)
                ticket.sale();

        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 60; i++)
                ticket.sale();

        }, "C").start();
    }
}

class Ticket2 {
    Lock lock = new ReentrantLock();
    private int number = 50;

    public void sale() {
        lock.lock();//加锁
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票，剩余:" + number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
